package com.pvdnc.tapkit.chat.ui.friend;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.pvdnc.nsocket.log.SLog;
import com.pvdnc.tapkit.chat.ChatService;
import com.pvdnc.tapkit.chat.MessageEntity;
import com.pvdnc.tapkit.chat.R;
import com.pvdnc.tapkit.chat.chat.client.ChatStart;
import com.pvdnc.tapkit.chat.chat.client.ClientInfo;
import com.pvdnc.tapkit.chat.chat.client.FriendReceiver;
import com.pvdnc.tapkit.chat.chat.client.MessageReceiver;
import com.pvdnc.tapkit.chat.chat.packet.GetFriendRequest;
import com.pvdnc.tapkit.chat.ui.ChatActivity;
import com.pvdnc.tapkit.utils.NotificationUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import jsc.kit.adapter.OnItemClickListener;
import jsc.kit.adapter.OnItemLongClickListener;

public class FriendActivity extends AppCompatActivity {
    private static final SLog LOG=new SLog(FriendActivity.class);

    public static void start(Context context){
        Intent intent=new Intent(context,FriendActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friend);
        initFriendView();
    }

    private SessionAdapter mSessionAdapter;

    private FriendReceiver mFriendReceiver=new FriendReceiver() {
        @Override
        public void onReceive(Context context, Map<String, ClientInfo> friendMap) {
            List<String> friendList=new ArrayList<>(friendMap.keySet());
            List<SessionEntity> entityList=mSessionAdapter.getData();
            //mSessionAdapter.clearData();
            for (String name:friendList){
                SessionEntity entity=create(name,"newly add friend");
                if(!entityList.contains(entity))
                    mSessionAdapter.addData(entity);
            }
            for (int i = 0; i < entityList.size(); i++) {
                String name=entityList.get(i).mOwner.mName;
                if(!friendList.contains(name)) {
                    LOG.d("remove offline client:"+name);
                    mSessionAdapter.removeData(i);
                }
            }
            lvwFriend.scrollToPosition(0);
        }
    };

    private MessageReceiver mMessageReceiver=new MessageReceiver() {
        @Override
        public void onReceive(Context context, MessageEntity entity) {
            List<SessionEntity> sessionEntityList= mSessionAdapter.getData();
            for (int i = 0; i < sessionEntityList.size(); i++) {
                SessionEntity sessionEntity=sessionEntityList.get(i);
                if(!entity.mName.equals(sessionEntity.mOwner.mName))
                    continue;
                //更新消息内容
                sessionEntity.mPreviewText=entity.mContent;
                if(entity.mLevel== NotificationUtils.LEVEL_IMPORTANT) {
                    mSessionAdapter.removeData(i);
                    mSessionAdapter.addData(0, sessionEntity);
                    break;
                }
                mSessionAdapter.updateData(i,sessionEntity);
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        LOG.d("onResume");

        mFriendReceiver.register();
        updateFriend();
        mMessageReceiver.register();
    }

    @Override
    protected void onPause() {
        super.onPause();
        LOG.d("onPause");
        mFriendReceiver.unregister();
        //mMessageReceiver.unregister();
    }

    private SessionEntity create(String name,String previewText){
        HeadNameEntity owner=new HeadNameEntity();
        owner.mName=name;
        SessionEntity entity=new SessionEntity();
        entity.mOwner=owner;
        entity.mPreviewText=previewText;
        return entity;
    }

    private RecyclerView lvwFriend;
    private void initFriendView(){
        lvwFriend= findViewById(R.id.lvwFriend);
        lvwFriend.setLayoutManager(new LinearLayoutManager(this));
        //设置Adapter
        mSessionAdapter=new SessionAdapter();
        mSessionAdapter.addHeader(new CenterTextEntity("Refresh"));
        mSessionAdapter.addData(create("DemoFriend","just stub"));
        mSessionAdapter.setOnItemClickListener(new OnItemClickListener<CenterTextEntity, SessionEntity, CenterTextEntity, CenterTextEntity>() {
            @Override
            public void onHeaderItemClick(@NonNull View headerItemView, int position, CenterTextEntity headerBean) {
                updateFriend();
            }

            @Override
            public void onDataItemClick(@NonNull View dataItemView, int position, SessionEntity dataBean) {
                startChat(dataBean);
            }

            @Override
            public void onFooterItemClick(@NonNull View footerItemView, int position, CenterTextEntity footerBean) {

            }

            @Override
            public void onEmptyItemClick(@NonNull View emptyItemView, int position, CenterTextEntity emptyBean) {

            }
        });
        mSessionAdapter.setOnItemLongClickListener(new OnItemLongClickListener<CenterTextEntity, SessionEntity, CenterTextEntity, CenterTextEntity>() {
            @Override
            public boolean onHeaderItemLongClick(@NonNull View headerItemView, int position, CenterTextEntity headerBean) {
                return false;
            }

            @Override
            public boolean onDataItemLongClick(@NonNull View dataItemView, final int position,
                                               final SessionEntity dataBean) {
                LOG.d("onDataItemLongClick");
                SessionPopup popup=new SessionPopup(FriendActivity.this);
                popup.setPositiveText("Chat");
                popup.setOnPositiveClick(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startChat(dataBean);
                    }
                });
                popup.setNegativeText("Delete");
                popup.setOnNegativeClick(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int index= mSessionAdapter.toDataIndex(position);
                        LOG.d("delete item by index:"+index);
                        mSessionAdapter.removeData(index);
                    }
                });
                popup.show(dataItemView);
                return true;
            }

            @Override
            public boolean onFooterItemLongClick(@NonNull View footerItemView, int position, CenterTextEntity footerBean) {
                return false;
            }

            @Override
            public boolean onEmptyItemLongClick(@NonNull View emptyItemView, int position, CenterTextEntity emptyBean) {
                return false;
            }
        });
        //绑定View
        mSessionAdapter.setHeaderLayoutId(R.layout.item_center_text);
        mSessionAdapter.setDataLayoutId(R.layout.item_session);
        mSessionAdapter.bindRecyclerView(lvwFriend);
    }

    private void startChat(SessionEntity dataBean){
        ChatStart start=new ChatStart();
        start.mSrcName=ChatService.get().getName();
        start.mToName=dataBean.mOwner.mName;
        LOG.d("start chat with client:"+start.mToName);
        ChatActivity.start(FriendActivity.this,start);
    }

    private void updateFriend(){
        ChatService.get().send(new GetFriendRequest(),false);
    }
}
